//数据库的名是"mydatebase.db"
var sqlite3 = require("sqlite3");
const fs = require('fs')
//创建数据库
var database
const path = "mydatebase.db"
async function server() {


    return new Promise(async resolve => {
        let flag = await fileExist()
        database = new sqlite3.Database(path, async (err) => {
            if (err) {
                console.log("new database error,", err.message);
            } else {
                if(!flag){
                    await database.run(`CREATE TABLE "t_codes" ("type"  TEXT,"data"  TEXT,"time"  TEXT);`,async err=>{
                        console.log("init database success");
                    })
                }else {
                    console.log("connect database success");
                }
            }
            resolve()
        });
    })

}
function fileExist(){
    return new Promise(resolve => {
        fs.exists(path, (exists) => {
            let flag = true
            if(!exists)
                flag = false
            resolve(flag)
        })
    })
}
async function add(table, arr) {
    console.log(`insert params ${arr}`)
    database.run(`insert into t_${table} values(?,?,?)`, arr, err => {
        let msg = err ? 'error' : 'success'
        console.log('insert ' + msg)
    })

}

async function del(table, commonSql) {
    database.run(`delete from t_${table} where ${commonSql}`, err => {
        let msg = err ? 'error' : 'success'
        console.log('delete ' + msg)
    })

}

function query(table, commonSql = '1=1') {

    return new Promise(resolve => {
        database.all(`select * from t_${table} where ${commonSql}`, (err, rows) => {
            let msg = err ? 'error' : 'success'
            console.log('query ' + msg)
            resolve(rows)
        })
    })

}

module.exports = {
    add, query, del, server
}

